package indi.kider.server.woniubus.service;

import indi.kider.common.constant.HouseReserveCons;
import indi.kider.common.constant.HouseStateCons;
import indi.kider.common.model.apabus.Destine;
import indi.kider.common.model.apabus.DestineQuery;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.woniubus.TenantVo;
import indi.kider.server.apabus.mapper.DestineMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vankid.common.model.base.CoreException;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@SuppressWarnings("ALL")
public class DestineServiceImpl implements DestineService {

    @Autowired
    private DestineMapper destineMapper;

    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private WoniuBusService woniuBusService;

    @Override
    public PageResponse<List<Map>> getDestinePageList(PageRequest<DestineQuery> request) {
        PageUtil.start(request);
        return PageUtil.getPageResponse(destineMapper.getDestineList(request.getQuery()));
    }

    @Transactional
    @Override
    public void destine(Destine destine) {
        destineMapper.insertSelective(destine);
        // 更新房屋状态。
        Houses house = new Houses();
        house.setId(destine.getHousesId());
        house.setState(HouseStateCons.RESERVE);
        house.setReleaseState(HouseReserveCons.NO_RESRVE);
        housesMapper.updateByPrimaryKeySelective(house);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public void displayDestine(Destine destine,TenantVo tenantVo) throws Exception{
        if(destine.getState() == 4){//签约
            tenantVo.setHouseId(destine.getHousesId());
            woniuBusService.rentHouse(tenantVo);
        }else{
            // 更新房屋状态。
            Houses house = new Houses();
            house.setId(destine.getHousesId());
            house.setState(HouseStateCons.VACANCY);
            housesMapper.updateByPrimaryKeySelective(house);
        }
        destine.setDestineName(tenantVo.getName());
        destine.setDestineTime(new Date());
        destineMapper.updateByPrimaryKeySelective(destine);
    }
}
